<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
    <!-- 页面头部 -->
    <header class="bg-white/80 backdrop-blur-sm shadow-lg border-b border-white/20">
      <div class="container mx-auto px-4 py-8">
        <div class="text-center">
          <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-purple-600 to-indigo-600 rounded-full mb-4 shadow-lg">
            <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
            </svg>
          </div>
          <h1 class="text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-600 bg-clip-text text-transparent">讨论区</h1>
          <p class="text-gray-600 mt-2 text-lg">分享想法，交流经验</p>
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 筛选和搜索区域 -->
      <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6 mb-6 border border-white/20">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div class="flex flex-wrap items-center gap-3">
            <button 
              v-for="category in categories" 
              :key="category.value"
              @click="selectedCategory = category.value"
              :class="[
                'px-6 py-3 border rounded-xl text-sm font-medium transition-all duration-200 transform hover:scale-105',
                selectedCategory === category.value
                  ? 'bg-gradient-to-r from-purple-500 to-purple-600 text-white border-purple-500 shadow-md'
                  : 'border-gray-300 text-gray-700 bg-white/80 backdrop-blur-sm hover:bg-gray-50 hover:shadow-md'
              ]"
            >
              {{ category.label }}
            </button>
          </div>
          <div class="flex items-center space-x-3">
            <div class="relative">
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索讨论..."
                class="w-64 px-4 py-3 pl-10 bg-white/80 backdrop-blur-sm border border-gray-300 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-purple-500/30 focus:border-purple-500 transition-all duration-200"
              >
              <svg class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
              </svg>
            </div>
            <button class="px-6 py-3 bg-gradient-to-r from-purple-500 to-purple-600 text-white text-sm font-medium rounded-xl hover:from-purple-600 hover:to-purple-700 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105">
              <svg class="w-4 h-4 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
              </svg>
              发起讨论
            </button>
          </div>
        </div>
      </div>

      <!-- 讨论列表 -->
      <div class="space-y-6">
        <!-- 加载状态 -->
        <div v-if="loading" class="flex justify-center items-center py-12">
          <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-500"></div>
          <span class="ml-3 text-gray-600 text-lg">加载中...</span>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="text-center py-12">
          <div class="w-16 h-16 mx-auto mb-4 bg-red-100 rounded-full flex items-center justify-center">
            <svg class="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
          </div>
          <h3 class="text-lg font-medium text-gray-900 mb-2">加载失败</h3>
          <p class="text-gray-500 mb-4">{{ error }}</p>
          <button @click="loadDiscussions" class="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors">
            重试
          </button>
        </div>

        <!-- 空状态 -->
        <div v-else-if="discussions.length === 0" class="text-center py-12">
          <div class="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
            <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
            </svg>
          </div>
          <h3 class="text-lg font-medium text-gray-900 mb-2">暂无讨论</h3>
          <p class="text-gray-500 mb-4">还没有人发起讨论</p>
          <button class="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors">
            发起第一个讨论
          </button>
        </div>

        <!-- 讨论卡片 -->
        <div v-else>
          <div 
            v-for="discussion in discussions" 
            :key="discussion.id"
            class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg border border-white/20 hover:shadow-xl transition-all duration-300 transform hover:scale-[1.02] cursor-pointer"
            @click="viewDiscussion(discussion)"
          >
            <div class="p-6">
              <div class="flex items-start justify-between mb-4">
                <div class="flex items-center space-x-3">
                  <img :src="discussion.author.avatar" alt="用户头像" class="w-12 h-12 rounded-full border-2 border-gray-200">
                  <div>
                    <h3 class="text-lg font-semibold text-gray-900">{{ discussion.title }}</h3>
                    <div class="flex items-center text-sm text-gray-500 mt-1">
                      <span class="font-medium">{{ discussion.author.username }}</span>
                      <span class="mx-2">·</span>
                      <span>{{ formatTime(discussion.created_at) }}</span>
                    </div>
                  </div>
                </div>
                <div class="flex items-center space-x-2">
                  <span v-if="discussion.is_pinned" class="px-2 py-1 bg-yellow-100 text-yellow-800 text-xs font-medium rounded-full">
                    置顶
                  </span>
                  <span class="px-2 py-1 bg-purple-100 text-purple-800 text-xs font-medium rounded-full">
                    {{ getCategoryText(discussion.category) }}
                  </span>
                </div>
              </div>
              
              <p class="text-gray-600 text-sm leading-relaxed mb-4 line-clamp-3">
                {{ discussion.summary || discussion.content.substring(0, 300) + '...' }}
              </p>
              
              <div class="flex items-center justify-between">
                <div class="flex items-center space-x-6 text-sm text-gray-500">
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                    </svg>
                    {{ discussion.view_count }} 次浏览
                  </span>
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                    </svg>
                    {{ discussion.like_count }} 个赞
                  </span>
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                    </svg>
                    评论
                  </span>
                </div>
                <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="discussions.length > 0" class="mt-8 flex justify-center">
        <nav class="relative z-0 inline-flex rounded-xl shadow-sm -space-x-px">
          <button
            :disabled="currentPage === 1"
            class="relative inline-flex items-center px-4 py-2 rounded-l-xl border border-gray-300 bg-white/80 backdrop-blur-sm text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
            @click="goToPage(currentPage - 1)"
          >
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
            </svg>
            上一页
          </button>
          <button
            v-for="page in visiblePages"
            :key="page"
            :class="[
              'relative inline-flex items-center px-4 py-2 border text-sm font-medium transition-all duration-200',
              page === currentPage
                ? 'z-10 bg-gradient-to-r from-purple-600 to-indigo-600 border-purple-600 text-white shadow-lg'
                : 'bg-white/80 backdrop-blur-sm border-gray-300 text-gray-500 hover:bg-gray-50'
            ]"
            @click="goToPage(page)"
          >
            {{ page }}
          </button>
          <button
            :disabled="currentPage === totalPages"
            class="relative inline-flex items-center px-4 py-2 rounded-r-xl border border-gray-300 bg-white/80 backdrop-blur-sm text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
            @click="goToPage(currentPage + 1)"
          >
            下一页
            <svg class="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
            </svg>
          </button>
        </nav>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { discussionApi } from '@/api/discussion'

const router = useRouter()

// 响应式数据
const discussions = ref<any[]>([])
const loading = ref(false)
const error = ref('')
const searchQuery = ref('')
const selectedCategory = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(1)

// 分类选项
const categories = ref([
  { value: 'all', label: '全部' },
  { value: 'general', label: '综合讨论' },
  { value: 'question', label: '题目讨论' },
  { value: 'contest', label: '竞赛讨论' },
  { value: 'feedback', label: '反馈建议' }
])

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, start + 4)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const loadDiscussions = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      category: selectedCategory.value !== 'all' ? selectedCategory.value : undefined,
      search: searchQuery.value || undefined
    }
    
    const response = await discussionApi.getDiscussions(params)
    
    if (response && response.data) {
      discussions.value = response.data.discussions || []
      totalPages.value = response.data.pagination?.total_page || 1
    } else {
      discussions.value = []
    }
  } catch (err: any) {
    console.error('加载讨论失败:', err)
    error.value = err.message || '加载讨论失败'
    discussions.value = []
  } finally {
    loading.value = false
  }
}

const viewDiscussion = (discussion: any) => {
  // 这里可以跳转到讨论详情页面
  console.log('查看讨论:', discussion)
}

const getCategoryText = (category: string) => {
  const categoryMap: Record<string, string> = {
    general: '综合讨论',
    question: '题目讨论',
    contest: '竞赛讨论',
    feedback: '反馈建议'
  }
  return categoryMap[category] || '综合讨论'
}

const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  } else {
    return date.toLocaleDateString()
  }
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadDiscussions()
  }
}

// 监听搜索和分类变化
const handleSearch = () => {
  currentPage.value = 1
  loadDiscussions()
}

// 初始化
onMounted(() => {
  loadDiscussions()
})
</script>

<style scoped>
.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
